package com.dlwx.parttimetalent.base;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.multidex.MultiDex;
import android.support.v4.app.NotificationCompat;

import com.baidu.mapapi.SDKInitializer;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.baidu.LocationService;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.service.MyReceiver;
import com.dlwx.parttimetalent.ui.MainActivity;
import com.dlwx.parttimetalent.utils.BackgroundUtil;
import com.dlwx.parttimetalent.utils.CityJson;
import com.dlwx.parttimetalent.utils.HxUtils;
import com.dlwx.parttimetalent.utils.JudgePhoneBrand;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.Utils;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.util.NetUtils;
import com.lzy.okgo.OkGo;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.tencent.bugly.Bugly;
import com.tencent.tauth.Tencent;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;


/**
 * Created by Administrator on 2017/6/24/024.
 */

public class MyApplication extends Application {
    public static String User_token;
    public static String chooseCity;
    public static String currentCity;
    public static String deposit;
    public static String TaskId;
    private SharedPreferences sp;
    public static int isFirstFragment;
    public static int isFirstActivity;
    public static int isIntegralFirest;
    private static MyApplication instance;
    public static CityJson.SanJiLianDBean sanJiLianDBean;
    private String apiToken;

    private int clientId;
    public static String HeadPic= Http.Logo;
    public static Tencent mTencent;
    public LocationService locationService;
    private Vibrator mVibrator;
    /**
     * 当前Acitity个数
     */
    private int activityAount = 0;

    private boolean isForeground;
    /**
     * Activity 生命周期监听，用于监控app前后台状态切换
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }

        @Override
        public void onActivityStarted(Activity activity) {
            if (activityAount == 0) {
                //app回到前台
                isForeground = true;
                SPUtils.put(getApplicationContext(),Constant.isForeground,isForeground);
            }
            activityAount++;
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }
        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            activityAount--;
            if (activityAount == 0) {
                isForeground = false;
                SPUtils.put(getApplicationContext(),Constant.isForeground,isForeground);
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        instance=this;
        Utils.init(this);
        WbSdk.install(this,new AuthInfo(this, Constant.APP_KEY, Constant.REDIRECT_URL, Constant.SCOPE));
        mTencent = Tencent.createInstance(Constant.QQ_APPID,this);
        sanJiLianDBean = CityJson.initJsonData(getApplicationContext());
//        CrashReport.initCrashReport(getApplicationContext(), "6a1ae2a31d", false);
        Bugly.init(getApplicationContext(), Constant.BUGLY_APPID, false);
        initHuanXin();
        initJiGuang();
        initBaidu();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //全局的读取超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//全局的写入超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
//全局的连接超时时间
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        OkGo.getInstance().init(this);

//                .setOkHttpClient(builder.build());
        //方法一：信任所有证书,不安全有风险
//        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
//        OkGo.getInstance().init(this);//必须调用初始
//        sp = getSharedPreferences(SPUtils.SP_MODE, MODE_PRIVATE);
//        User_token = sp.getString(SPUtils.Token, "b088ab7b4b51de8808aa290c69b83d8a");//3419d6576aa8078b30c7850c5053c986
//        chooseCity=sp.getString(SharePrUtiles.chooseCity,"");
//        currentCity=sp.getString(SharePrUtiles.currentCity,"");
//        deposit=sp.getString(SharePrUtiles.deposit,"");
//        TaskId=sp.getString(SharePrUtiles.task_id,"");

//        initYouMeng();
//        JPushInterface.setDebugMode(true);//如果时正式版就改成false
//        JPushInterface.init(this);
//        DemoHelper.getInstance().init(this);
    }

    private void initBaidu() {
        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
        SDKInitializer.initialize(getApplicationContext());
    }

    private void initJiGuang() {
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        JPushInterface.setLatestNotificationNumber(this, 3);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        MyReceiver mReceiver = new MyReceiver();
        registerReceiver(mReceiver, intentFilter);
//        String userId= (String) SPUtils.get(this,Constant.USER_ID,"");
//        String user_id = sp.getString(userId,"");
//        if (user_id != null) {
//            Set<String> tags = new HashSet<>();
//            tags.add(user_id);
//            JPushInterface.setTags(getApplicationContext(),1,tags);
//        }
    }

    private void initHuanXin() {
        EMOptions options = new EMOptions();
// 默认添加好友时，是不需要验证的，改成需要验证
//        options.setAcceptInvitationAlways(false);
        // 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);
        options.setAutoLogin(true);
//初始化
        EMMessageListener msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                String conId = messages.get(0).conversationId();
                EaseUI.getInstance().getNotifier().vibrateAndPlayTone(messages.get(0));
                //收到消息
                Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),0,intent, PendingIntent.FLAG_UPDATE_CURRENT);
                //获取NotificationManager实例
                NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                //实例化NotificationCompat.Builde并设置相关属性
                Notification builder=new NotificationCompat.Builder(getApplicationContext(),"约神消息")
                        //设置小图标
                        .setSmallIcon(R.mipmap.logopro)
                        //设置通知标题
                        .setContentTitle("约神")
                        //设置通知内容
                        .setContentText("你有一条新信息")
                        .setContentIntent(pendingIntent)
                        //设置点击之后notification消失
                        .setAutoCancel(true)
                        .build();
                //设置通知时间，默认为系统发出通知的时间，通常不用设置
                //.setWhen(System.currentTimeMillis());
                //通过builder.build()方法生成Notification对象,并发送通知,id=1
                Boolean isForeground= BackgroundUtil.getRunningAppProcesses(getApplicationContext(), getPackageName());
                if (JudgePhoneBrand.SYS_MIUI.equals(JudgePhoneBrand.getSystem())) {
                    if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.LOLLIPOP){
                        isForeground= BackgroundUtil.getRunningTask(getApplicationContext(), getPackageName());
                    }
                }
                if(!isForeground){
                    notifyManager.notify(1, builder);
                }
//                发送广播
                Intent i=new Intent();
                i.putExtra("conId",conId);
                i.setAction(Constant.ACTION_HX);
                sendBroadcast(i);
                PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
                boolean isScreenOn = false;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
                    isScreenOn = pm.isInteractive();
                }else{
                    isScreenOn = pm.isScreenOn();
                }
                if(!isScreenOn){

                    lightScreen(getApplicationContext());
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
                LogUtils.i("---1");
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
                //收到已读回执
                LogUtils.i("---2");
            }

            @Override
            public void onMessageDelivered(List<EMMessage> messages) {
                //收到已送达回执
                //                发送广播
                String conId = messages.get(0).conversationId();
                Intent i=new Intent();
                i.putExtra("conId",conId);
                i.setAction(Constant.ACTION_HX);
                sendBroadcast(i);
                LogUtils.i("---3");
            }
            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                //消息被撤回
                LogUtils.i("---5");
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
                LogUtils.i("---6");
            }
        };
        if(EaseUI.getInstance().init(this, options)){
//在做打包混淆时，关闭debug模式，避免消耗不必要的资源
           EMClient.getInstance().setDebugMode(true);
            EMClient.getInstance().chatManager().addMessageListener(msgListener);
            EMClient.getInstance().addConnectionListener(new EMConnectionListener() {
                @Override
                public void onConnected() {
                }
                @Override
                public void onDisconnected(final int error) {
                    boolean b= (boolean) SPUtils.get(getApplicationContext(),Constant.isLogin,false);
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        if(b){
//                        HxUtils.loginOut();
                            Intent i=new Intent();
                            i.setAction(Constant.RECEIVER_ACCOUNT);
                            i.putExtra("type",Constant.MSG_ACCOUNT_REPEAT);
                            sendBroadcast(i);
                        }
                    } else {
                        if (NetUtils.hasNetwork(getApplicationContext())){
                            int userid= (int) SPUtils.get(getApplicationContext(),Constant.USER_ID,0);
                            if(userid!=0){
                                if(b){
                                    HxUtils.login(userid+"");
                                }
                            }
                        }
                        //连接不到聊天服务器
                        else{}
                        //当前网络不可用，请检查网络设置
                    }
                }
            });
        } ;
        EaseUI easeUI = EaseUI.getInstance();

        easeUI.setSettingsProvider(new EaseUI.EaseSettingsProvider() {
            @Override
            public boolean isMsgNotifyAllowed(EMMessage message) {
                return true;
            }

            @Override
            public boolean isMsgSoundAllowed(EMMessage message) {

                return true;
            }

            @Override
            public boolean isMsgVibrateAllowed(EMMessage message) {
                return false;
            }

            @Override
            public boolean isSpeakerOpened() {
                return false;
            }
        });
    }

//    private void initYouMeng() {
//        PlatformConfig.setWeixin("wxad974f02fd79d39a", "b4f1d118ba64db25f909100439b7e8cd");
//        PlatformConfig.setQQZone("1106338831", "S3VTy2TnPZHr91NI");
//        PlatformConfig.setSinaWeibo("1241390185", "ecf487408bf752b37c84459de314a2b9", "http://sns.whalecloud.com/sina2/callback");
//        UMShareAPI.get(this);
//
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        MyReceiver mReceiver = new MyReceiver();
//        registerReceiver(mReceiver, intentFilter);
//        registerReceiver(mReceiver, intentFilter);
//        String userid = sp.getString(SPUtils.User_id, "");
//        if (userid != null) {
//            //极光设置tag
//            Set<String> tags = new HashSet<>();
//            tags.add(userid);
//            JPushInterface.setTags(getApplicationContext(), 1, tags);
//        }
//    }
//
//
//    public void setCity(String chooseCity) {
//        this.chooseCity = chooseCity;
//    }
//
//    public void setUser_token(String token) {
//        this.User_token = token;
//    }
//
//    public void setDeposit(String deposit) {
//        this.deposit = deposit;
//    }
//
//    public void setTaskId(String taskId) {
//        this.TaskId = taskId;
//    }
//    public static MyApplication getInstance() {
//        return instance;
//    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public String getApiToken() {
        return apiToken;
    }

    public void setApiToken(String apiToken) {
        this.apiToken = apiToken;
    }

    public int getClientId() {
        return clientId;
    }

    public void setClientId(int clientId) {
        this.clientId = clientId;
    }

    /**
     * 点亮屏幕
     */
    private void lightScreen(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            if (!pm.isInteractive()) {
                wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                        | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
                wakeLock.acquire();
            }
        } else {
            if (!pm.isScreenOn()) {
                wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                        PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
                wakeLock.acquire();
            }
        }
      /*  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(wakeLock.isHeld()){
                    wakeLock.release();
                }
            }
        },3000);*/
    }
}
